<template>
  <div class="main-box-admin">
    <el-breadcrumb separator="/" style="font-size: 18px;">
      <el-breadcrumb-item :to="{ path: '/TanHome/ManageEnergy' }">物质输入管理首页</el-breadcrumb-item>
      <el-breadcrumb-item>物质输入列表</el-breadcrumb-item>
    </el-breadcrumb>
    <br>
    <div>
      <div class="flex-box-header">
        <div class="energyleft">
          <el-form>
            <el-tag style="font-size: 13px;">输入物质名称：</el-tag>
            <el-form-item style="display: inline-block">
              <el-input v-model="objectName" placeholder="请输入物质名称" size="small"></el-input>
            </el-form-item>
            <el-button class="form-item-inline" size="small" @click="searchenergey" plain
              icon="el-icon-search">查询</el-button>
            <el-button class="form-item-inline" type="success" size="small" @click="getAllEnergey" plain
              icon="el-icon-search">显示全部物质</el-button>
          </el-form>
        </div>
        <div class="energyright">
          <el-form>
            <el-button class="form-item-inline" type="primary" size="small" @click="insertEnergy">新增物质</el-button>
            <el-button class="form-item-inline" type="primary" size="small" @click="getexcelEnergy">导入物质</el-button>
          </el-form>
        </div>
      </div>
      <div class="table_container">
        <el-table :data="tableData" style="width: 100%;font-size: 15px;" size="small">
          <el-table-column prop="objectName" label="物质名称"></el-table-column>
          <el-table-column prop="objectPurpose" label="物质用途"></el-table-column>
          <el-table-column prop="objectAmount" label="物质量"></el-table-column>
          <el-table-column prop="objectSource" label="物质来源"></el-table-column>
          <el-table-column prop="objectYear" label="输入时间（年）"></el-table-column>
          <el-table-column prop="objectMonth" label="输入时间（月）"></el-table-column>
          <el-table-column label="操作" width="300">
            <template slot-scope="scope">
              <el-button @click="updateObject(scope.row)" type="warning" plain size="small"
                icon="el-icon-edit">修改</el-button>
              <el-button @click="deleteEnergy(scope.row)" type="danger" plain size="small"
                icon="el-icon-delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 换页菜单 -->
        <div style="text-align:center; margin:20px">
          <el-pagination background @current-change="handleCurrentChange" :page-size="limit" :current-page="1"
            layout="total, prev, pager, next" :total="total">
          </el-pagination>
        </div>
      </div>
      <div class="upload-image">
        <el-dialog title="添加物质信息" :visible.sync="energyInsertForm" width="40%">
          <el-form :model="newEnergyData" ref="ruleForm" label-width="180px">
            <el-form-item label="物质名称" prop="objectName">
              <el-input v-model="newEnergyData.objectName" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="物质用途" prop="objectPurpose">
              <el-input v-model="newEnergyData.objectPurpose" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="物质量" prop="objectAmount">
              <el-input v-model="newEnergyData.objectAmount" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="物质来源" prop="objectSource">
              <el-input v-model="newEnergyData.objectSource" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="输入时间（年）" prop="objectYear">
              <el-date-picker v-model="newEnergyData.objectYear" type="year" value-format='yyyy' placeholder="选择年">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="输入时间（月）" prop="objectMonth">
              <!--<el-date-picker
                v-model="newEnergyData.energyMonth"
                type="month"
                value-format='MM'
                placeholder="选择月">
              </el-date-picker>-->
              <el-input v-model="newEnergyData.objectMonth" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="insertNewEnergy">立即创建</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div class="upload-image">
        <el-dialog title="修改物质信息" :visible.sync="energyUpdateForm" width="40%">
          <el-form :model="updateEnergyData" ref="ruleForm" label-width="180px">
            <el-form-item label="物质名称" prop="objectName">
              <el-input v-model="updateEnergyData.objectName" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="物质用途" prop="objectPurpose">
              <el-input v-model="updateEnergyData.objectPurpose" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="物质量" prop="objectAmount">
              <el-input v-model="updateEnergyData.objectAmount" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="物质来源" prop="objectSource">
              <el-input v-model="updateEnergyData.objectSource" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="输入时间（年）" prop="objectYear">
              <el-date-picker v-model="updateEnergyData.objectYear" type="year" value-format='yyyy' placeholder="选择年">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="输入时间（月）" prop="objectMonth">
              <el-input v-model="updateEnergyData.objectMonth" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="modifyEnergy()">立即修改</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div class="upload-image" style="width: 300px">
        <el-dialog class="self_define" title="导入物质列表" :close-on-click-modal='false' :visible.sync="energyAddForm"
          width="40%">
          <el-form :model="fileRes"  ref="ruleForm" label-width="100px">
            <el-form-item label="" ref="uploadElement" prop="photoUrl" style="margin: 0 auto">
              <el-upload class="upload-demo" ref="upload" drag :action="UploadEnergyUrl()" multiple :auto-upload="false"
                :on-success="handleSuccessEnergy" :on-error="uploadEnergyError" :before-upload="getFileType" :limit="5"
                :file-list="fileList" name="file">
                <i class="el-icon-upload"></i>
                <div slot="tip" class="el-upload__tip">只能上传一个.xlsx 文件</div>
                <div slot="tip" class="el-upload__tip" style="width:100%; word-break:break-all;" >
                  传入的xlsx文件第一行必须为为表头(物质名称，物质用途，物质量，输入时间（年），输入时间（月），物质来源)</div>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="addNewEnergy">确定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import { publicNetworkIpAndPort } from "../../api/globalVar";
import { getAllEnergey, searchEnergyByName } from "../../api/user";

export default {
  data() {
    return {
      current: 1,
      size: 10,
      cur: 1,
      fileRes: {},
      updateEnergyData: {},
      newEnergyData: {},
      fileList: [],
      tableData: [],
      objectName: '',
      energyAddForm: false,
      energyUpdateForm: false,
      energyInsertForm: false,
      limit: 10,
      total: 0,
    }
  },
  mounted:function() {
    this.getAllEnergey()
  },
  activated() {
    this.getAllEnergey()
  },
  methods: {
    /**
     *获取时间
     */
    formatDate(date, format) {
      let time = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        'S+': date.getMilliseconds()
      }
      if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (let k in time) {
        if (new RegExp('(' + k + ')').test(format)) {
          format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? time[k] : ('00' + time[k]).substr(('' + time[k]).length));
        }
      }
      return format;
    },
    insertNewEnergy() {
      if (this.newEnergyData["objectName"] === "" || this.newEnergyData["objectPurpose"] === '' || this.newEnergyData["objectAmount"] === '' || this.newEnergyData["objectSource"] === '') {
        this.$message.error("请将表单信息填写完整");
        return;
      } else {
        //this.$refs.upload.submit();
        this.handleEnergy();
      }
    },
    handleEnergy() {
      console.log("this.newEnergyData", this.newEnergyData)
      // let aData = new Date();
      // let str=this.formatDate(aData, "yyyy");
      // this.newEnergyData.energyYear=str;
      // console.log("this.newEnergyData.energyYear",this.newEnergyData.energyYear)
      axios.post(publicNetworkIpAndPort() + "/api/energyConsumption/addEnergyConsumption", this.newEnergyData).then((res) => {
        //  //debugger
        console.log("res.data", res.data)
        if (res.data.code == 200) {
          this.$message.success(res.data.data);
        } else {
          this.$message.error(res.data.message);
        }
      }).catch(() => {

      }).finally(() => {
        this.getAllEnergey();
        this.energyInsertForm = false;
        this.newEnergyData = {};
      });//会把返回的结果放在.then里。
    },
    insertEnergy() {
      this.energyInsertForm = true;
    },
    updateObject(row) {
      this.updateEnergyData = row;
      this.energyUpdateForm = true;
      // console.log("row:",row)
      this.updateEnergyData.objectYear = this.updateEnergyData.objectYear.toString();
    },
    modifyEnergy() {
      if (this.updateEnergyData["objectName"] === "" || this.updateEnergyData["objectPurpose"] === '' || this.updateEnergyData["objectAmount"] === '' || this.updateEnergyData["objectSource"] === '') {
        this.$message.error("请将表单信息填写完整");
        return;
      }
      console.log("this.updateEnergyData:",this.updateEnergyData)
      axios.post(publicNetworkIpAndPort() + "/api/energyConsumption/updateEnergyConsumption", this.updateEnergyData).then((res) => {
        // //debugger
        console.log("修改能耗啦")
        console.log("res.data", res.data)
        if (res.data.code == 200) {
          this.$message.success(res.data.data);
        } else {
          this.$message.error(res.data.message);
        }
      }).catch(() => {
      }).finally(() => {
        this.getAllEnergey();
        this.energyUpdateForm = false;
        this.updateEnergyData = {};

      });

    },
    deleteEnergy(row) {
      // //debugger
      console.log("删除id:", row.id)
      var objectConsumptionId = row.id
      console.log("energyConsumptionId", objectConsumptionId)
      this.$confirm("此操作永久删除当前信息，是否继续？", "提示", { type: "info" }).then(() => {
        axios.get(publicNetworkIpAndPort() + "/api/energyConsumption/deleteEnergyConsumptionById?objectConsumptionId=" + objectConsumptionId).then((res) => {
          if (res.data.code === 200) {
            this.$message.success("删除成功")
            // 为了在删除最后一页的最后一条数据时能成功跳转回最后一页的上一页（pageSize=1时不生效）
            let totalPage = Math.ceil((this.total - 1) / this.size)
            let currentPage = this.current > totalPage ? totalPage : this.current
            this.current = currentPage < 1 ? 1 : currentPage
          } else {
            this.$message.error(res.data.message)
          }
          console.log("res", res)
        }).catch(() => {
        }).finally(() => {
          this.tableData.length = this.tableData.length - 1;
          if (this.tableData.length === 0) {
            this.cur = this.cur - 1;
            if (this.cur === 0) this.cur = 1;
          }
          this.getAllEnergey();
        });
      }).catch(() => {
        this.$message.info("取消操作");
      });
    },
    handleCurrentChange(val) {
      this.current = val
      this.getAllEnergey()
    },
    getFileType(file) {
      console.log("filetype")
      console.log("文件类型")
      console.log(file.type)
      if (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        return true;
      } else {
        this.$message({
          message: "上传文件只能是xlsx格式!",
          type: "warning",
        });
        return false;
      }
    },
    handleSuccessEnergy(res) {
      // //debugger
      console.log(res.data)
      console.log(res.code)
      if (res.code === 200) {
        this.$refs.upload.clearFiles();
        this.$message.success("文件上传成功")
        this.energyAddForm = false;
        this.fileRes = {};
        this.getAllEnergey();
      } else {
        this.$refs.upload.clearFiles();
        this.$message.error(res.message);
        this.energyAddForm = false;
        this.fileRes = {};
      }
    },
    uploadEnergyError() {
      this.$message.error("请选择.xlsx进行上传");
    },
    UploadEnergyUrl: function () {
      console.log("上传能耗啦")
      return publicNetworkIpAndPort() + "/api/energyConsumption/excelEnergyConsumption";
    },
    addNewEnergy() {
      var files = this.$refs.upload.uploadFiles
      if (files.length == 0) {
        this.$message.error("请选择上传的文件");
        return;
      }
      this.$refs.upload.submit();
    },
    searchenergey() {
      if (this.objectName !== '')
        searchEnergyByName({ current: this.current, size: this.size, objectName: this.objectName }).then(res => {
          // //debugger
          console.log("搜索this.energyName")
          console.log(this.energyName)
          console.log(res)
          console.log("llalalallalal")
          // //debugger
          this.tableData = res.data.records
          this.total = res.data.total;
          console.log(res.data.total);
        }).catch(() => {
        }).finally(() => {
        });

    },
    getAllEnergey() {
      getAllEnergey({ current: this.current, size: this.size }).then(res => {
        console.log("能耗列表res")
        console.log(res)
        this.tableData = res.data.records
        this.total = res.data.total;
        console.log(res.data.total);
      })
    },
    getexcelEnergy() {
      // //debugger
      this.energyAddForm = true
    },
  }
}

</script>
<style>
.energyleft,
.energyright {
  display: inline-block;
}

.energyright {
  vertical-align: top !important;
  margin-bottom: 19px;
}

.el-table th.el-table__cell {
  background-color: skyblue;
  color: #000;
  font-size: 15px;
  height: 50px;
}

.el-table,
.el-table__expanded-cell {
  background-color: transparent;
}

.el-table th,
.el-table tr {
  background-color: transparent;
}

.el-table__body tr:hover>td {
  background-color: skyblue !important;
}

.form-item-inline {
  font-size: 13px;
}

.el-table__fixed {
  height: 100% !important;
}

.main-box-admin {
  width: 94%;
  margin: 0 auto;
  text-align: left;
  padding: 3%;
}

.flex-box-header {
  margin-left: 20px;
  margin-right: 15px;
  margin-top: 15px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
